<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="司机账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入司机账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="司机昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入司机昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="司机邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入司机邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="司机性别" prop="sex">
        <el-select
          v-model="queryParams.sex"
          placeholder="请选择司机性别"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="驾驶证号码" prop="drivingLicenseNumber">
        <el-input
          v-model="queryParams.drivingLicenseNumber"
          placeholder="请输入驾驶证号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:driver:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:driver:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:driver:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:driver:import']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:driver:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="driverList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="司机id" align="center" prop="driverId" />
      <el-table-column label="司机账号" align="center" prop="userName" width="150"/>
      <el-table-column
        label="驾驶证号码"
        align="center"
        prop="drivingLicenseNumber"
        width="150"
      />
      <el-table-column
        label="车牌号"
        align="center"
        prop="licensePlate"
        width="150"
      >
        <template slot-scope="scope">
          {{
            scope.row.licensePlate != null ? scope.row.licensePlate : "未出车"
          }}
        </template>
      </el-table-column>
      <el-table-column label="行为分" align="center" prop="driverScore" />
      <el-table-column label="司机昵称" align="center" prop="nickName"  width="150"/>
      <!-- <el-table-column label="司机类型" align="center" prop="userType" /> -->
      <el-table-column label="司机邮箱" align="center" prop="email"  width="180" />
      <el-table-column label="手机号码" align="center" prop="phoneNumber"  width="150"/>
      <el-table-column label="司机性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="驾照证照片"
        align="center"
        prop="drivingLicenseImage"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview
            :src="scope.row.drivingLicenseImage"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column label="接单状态" align="center" prop="travelStatus">
        <template slot-scope="scope">
          <el-tag :type=getTagType(scope.row.travelStatus)>
            {{ getTravelStatusText(scope.row.travelStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="150">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status === '0'"
            :active-text="'启用'"
            :inactive-text="'禁用'"
            v-hasPermi="['system:driver:edit']"
            @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="车辆信息id" align="center" prop="carId" /> -->
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy" />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
         width="180"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:driver:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:driver:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改司机管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="司机账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入司机账号" />
        </el-form-item>

        <!-- <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password"/>
        </el-form-item> -->

        <el-form-item label="司机昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入司机昵称" />
        </el-form-item>

        <el-form-item label="头像地址" prop="avatar">
          <image-upload v-model="form.avatar" :limit="limit" />
        </el-form-item>
        <el-form-item label="驾照照片" prop="drivingLicenseImage">
          <image-upload v-model="form.drivingLicenseImage" :limit="limit" />
        </el-form-item>
        <el-form-item label="驾驶证号" prop="drivingLicenseNumber">
          <el-input
            v-model="form.drivingLicenseNumber"
            placeholder="请输入驾驶证号码"
          />
        </el-form-item>

        <el-form-item label="司机邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入司机邮箱" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="司机性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择司机性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">
                                <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                              </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDriver,
  getDriver,
  delDriver,
  addDriver,
  updateDriver,
} from "@/api/system/driver";
import { getToken } from "@/utils/auth";

export default {
  name: "Driver",
  dicts: ["sys_user_sex"],
  data() {
    var checkEmail = (rule, value, callback) => {
      // 检查电子邮件字段是否为空
      if (!value) {
        callback(new Error("请输入电子邮件地址"));
        return;
      }

      // 使用正则表达式验证电子邮件格式
      const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailPattern.test(value)) {
        callback(new Error("请输入有效的电子邮件地址"));
        return;
      }

      // 验证成功，调用 callback() 表示验证通过
      callback();
    };
    var checkPhone = (rule, value, callback) => {
      // 检查电话号码字段是否为空
      if (!value) {
        callback(new Error("请输入电话号码"));
        return;
      }

      // 使用正则表达式验证电话号码格式
      const phonePattern = /^1[3-9]\d{9}$/;
      if (!phonePattern.test(value)) {
        callback(new Error("请输入有效的手机号码"));
        return;
      }

      // 验证成功，调用 callback() 表示验证通过
      callback();
    };
    return {
      //能上传几张图片
      limit:1,
      //接单状态列表
      orderReceivingStatusList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 司机管理表格数据
      driverList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        nickName: null,
        email: null,
        phoneNumber: null,
        sex: null,
        drivingLicenseNumber: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/driver/importData",
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "司机账号不能为空", trigger: "blur" },
          { min: 11, max: 11, message: "长度11个字符", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "司机昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 8, max: 24, message: "长度8到24个字符", trigger: "blur" },
        ],
        drivingLicenseNumber: [
          { required: true, message: "驾驶证号码不能为空", trigger: "blur" },
          // { min: 8, max: 24, message: '长度8到24个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        avatar:[
          { required: true, message: "头像不能为空", trigger: "blur" },
        ],
        drivingLicenseImage:[
          { required: true, message: "驾照图片不能为空", trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
        sex: [{ required: true, message: "性别不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSwitchChange(row) {
      row.status = row.status === "0" ? "1" : "0";
      let form = {};
      form.status = row.status;
      form.driverId = row.driverId;
      console.log("状态已更改:", row.status);
      // 这里可以添加其他处理逻辑，比如更新服务器数据等
      if (form.driverId != null) {
        updateDriver(form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
        });
      }
    },
    //显示接单状态标签
    getTagType(travelStatus) {
      switch (travelStatus) {
        case  0 :
          return 'warning';
        case  1 :
          return 'success';
        case  2:
          return 'danger';
        default:
          return 'info'; // 默认标签类型
      }
    },
    getTravelStatusText(travelStatus) {
      switch (travelStatus) {
        case 0 :
          return "接单中";
        case 1 :
          return "已接单";
        case 2 :
          return "已取消";
        default:
          return "未知状态"; // 默认文本
      }
    },
    /** 查询司机管理列表 */
    getList() {
      this.loading = true;
      listDriver(this.queryParams).then((response) => {
        this.driverList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        driverId: null,
        carId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        userName: null,
        nickName: null,
        password: null,
        userType: null,
        email: null,
        phoneNumber: null,
        sex: null,
        avatar: null,
        drivingLicenseImage: null,
        drivingLicenseNumber: null,
        delFlag: null,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.driverId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加司机管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const driverId = row.driverId || this.ids;
      getDriver(driverId).then((response) => {
        this.form = response.data;
        this.form.password = null;
        this.open = true;
        this.title = "修改司机管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.driverId != null) {
            updateDriver(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDriver(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const driverIds = row.driverId || this.ids;
      this.$modal
        .confirm('是否确认删除司机管理编号为"' + driverIds + '"的数据项？')
        .then(function () {
          return delDriver(driverIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/driver/export",
        {
          ...this.queryParams,
        },
        `司机管理.xlsx`
      );
    },
    // ======================  导入相关方法 start ===================
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "司机管理导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/driver/importTemplate",
        {},
        `司机管理导入模板.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // ======================  导入相关方法 end ===================
  },
};
</script>

